[[...path]].page.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import React, { useEffect } from 'react';
  2. import { isClient, pagePathUtils } from '@growi/core';
  3. import { isValidObjectId } from 'mongoose';
  4. import {
  5. NextPage, GetServerSideProps, GetServerSidePropsContext,
  6. } from 'next';
  7. import Head from 'next/head';
  8. import { useRouter } from 'next/router';
  9. // import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  10. // import { PageComments } from '~/components/PageComment/PageComments';
  11. // import { useTranslation } from '~/i18n';
  12. import { isPopulated } from '~/interfaces/common';
  13. import { CrowiRequest } from '~/interfaces/crowi-request';
  14. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  15. // import { useIndentSize } from '~/stores/editor';
  16. // import { useRendererSettings } from '~/stores/renderer';
  17. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  18. import { IPageWithMeta } from '~/interfaces/page';
  19. import { PageModel } from '~/server/models/page';
  20. import { serializeUserSecurely } from '~/server/models/serializers/user-serializer';
  21. import { useSWRxCurrentPage, useSWRxPageInfo } from '~/stores/page';
  22. import loggerFactory from '~/utils/logger';
  23. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  24. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  25. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  26. // import DisplaySwitcher from '../client/js/components/Page/DisplaySwitcher';
  27. import { BasicLayout } from '../components/BasicLayout';
  28. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  29. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  30. import {
  31. useCurrentUser, useCurrentPagePath,
  32. useOwnerOfCurrentPage,
  33. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  34. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  35. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  36. useAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri, useMathJax, useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault,
  37. } from '../stores/context';
  38. import { CommonProps, getServerSideCommonProps, useCustomTitle } from './commons';
  39. // import { useCurrentPageSWR } from '../stores/page';
  40. const logger = loggerFactory('growi:pages:all');
  41. const { isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  42. type Props = CommonProps & {
  43. currentUser: string,
  44. pageWithMetaStr: string,
  45. // pageUser?: any,
  46. // redirectTo?: string;
  47. // redirectFrom?: string;
  48. // shareLinkId?: string;
  49. isForbidden: boolean,
  50. isNotFound: boolean,
  51. // isAbleToDeleteCompletely: boolean,
  52. isSearchServiceConfigured: boolean,
  53. isSearchServiceReachable: boolean,
  54. isSearchScopeChildrenAsDefault: boolean,
  55. // isMailerSetup: boolean,
  56. // isAclEnabled: boolean,
  57. // hasSlackConfig: boolean,
  58. // drawioUri: string,
  59. // hackmdUri: string,
  60. // mathJax: string,
  61. // noCdn: string,
  62. // highlightJsStyle: string,
  63. // isAllReplyShown: boolean,
  64. // isContainerFluid: boolean,
  65. // editorConfig: any,
  66. // isEnabledStaleNotification: boolean,
  67. // isEnabledLinebreaks: boolean,
  68. // isEnabledLinebreaksInComments: boolean,
  69. // adminPreferredIndentSize: number,
  70. // isIndentSizeForced: boolean,
  71. };
  72. const GrowiPage: NextPage<Props> = (props: Props) => {
  73. // const { t } = useTranslation();
  74. const router = useRouter();
  75. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  76. // commons
  77. useAppTitle(props.appTitle);
  78. useSiteUrl(props.siteUrl);
  79. // useEditorConfig(props.editorConfig);
  80. useConfidential(props.confidential);
  81. useCsrfToken(props.csrfToken);
  82. // page
  83. useCurrentPagePath(props.currentPathname);
  84. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  85. // useIsForbidden(props.isForbidden);
  86. // useNotFound(props.isNotFound);
  87. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  88. // useShared(isSharedPage(props.currentPagePath));
  89. // useShareLinkId(props.shareLinkId);
  90. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  91. // useIsSharedUser(props.currentUser == null && isSharedPage(props.currentPagePath));
  92. // useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  93. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  94. useIsSearchServiceReachable(props.isSearchServiceReachable);
  95. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  96. // useIsMailerSetup(props.isMailerSetup);
  97. // useAclEnabled(props.isAclEnabled);
  98. // useHasSlackConfig(props.hasSlackConfig);
  99. // useDrawioUri(props.drawioUri);
  100. // useHackmdUri(props.hackmdUri);
  101. // useMathJax(props.mathJax);
  102. // useNoCdn(props.noCdn);
  103. // useIndentSize(props.adminPreferredIndentSize);
  104. // useRendererSettings({
  105. // isEnabledLinebreaks: props.isEnabledLinebreaks,
  106. // isEnabledLinebreaksInComments: props.isEnabledLinebreaksInComments,
  107. // adminPreferredIndentSize: props.adminPreferredIndentSize,
  108. // isIndentSizeForced: props.isIndentSizeForced,
  109. // });
  110. // const { data: editorMode } = useEditorMode();
  111. let pageWithMeta: IPageWithMeta | undefined;
  112. if (props.pageWithMetaStr != null) {
  113. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  114. }
  115. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  116. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  117. // sync pathname
  118. useEffect(() => {
  119. if (isClient() && window.location.pathname !== props.currentPathname) {
  120. router.replace(props.currentPathname, undefined, { shallow: true });
  121. }
  122. }, [props.currentPathname, router]);
  123. const classNames: string[] = [];
  124. // switch (editorMode) {
  125. // case EditorMode.Editor:
  126. // classNames.push('on-edit', 'builtin-editor');
  127. // break;
  128. // case EditorMode.HackMD:
  129. // classNames.push('on-edit', 'hackmd');
  130. // break;
  131. // }
  132. // if (props.isContainerFluid) {
  133. // classNames.push('growi-layout-fluid');
  134. // }
  135. // if (page == null) {
  136. // classNames.push('not-found-page');
  137. // }
  138. // // Rewrite browser url by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  139. // useEffect(() => {
  140. // if (props.redirectTo != null) {
  141. // router.push('/[[...path]]', props.redirectTo, { shallow: true });
  142. // }
  143. // // eslint-disable-next-line react-hooks/exhaustive-deps
  144. // }, []);
  145. return (
  146. <>
  147. <Head>
  148. {/*
  149. {renderScriptTagByName('drawio-viewer')}
  150. {renderScriptTagByName('mathjax')}
  151. {renderScriptTagByName('highlight-addons')}
  152. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  153. */}
  154. </Head>
  155. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  156. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  157. <header className="py-0">
  158. {/* <GrowiSubNavigation /> */}
  159. GrowiSubNavigation
  160. </header>
  161. <div className="d-edit-none">
  162. {/* <GrowiSubNavigationSwitcher /> */}
  163. GrowiSubNavigationSwitcher
  164. </div>
  165. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  166. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  167. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  168. <div className="row">
  169. <div className="col grw-page-content-container">
  170. <div id="content-main" className="content-main grw-container-convertible">
  171. {/* <PageAlerts /> */}
  172. PageAlerts<br />
  173. {/* <DisplaySwitcher /> */}
  174. DisplaySwitcher<br />
  175. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  176. {/* <PageStatusAlert /> */}
  177. PageStatusAlert
  178. </div>
  179. </div>
  180. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  181. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  182. <div id="revision-toc-content" className="revision-toc-content"></div>
  183. </div>
  184. </div> */}
  185. </div>
  186. </div>
  187. <footer>
  188. {/* <PageComments /> */}
  189. PageComments
  190. <p>
  191. { pageWithMeta != null && isPopulated(pageWithMeta.data.revision) && pageWithMeta.data.revision.body }
  192. </p>
  193. </footer>
  194. </BasicLayout>
  195. </>
  196. );
  197. };
  198. async function injectPageInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  199. const req: CrowiRequest = context.req as CrowiRequest;
  200. const { crowi } = req;
  201. const Page = crowi.model('Page');
  202. const { pageService } = crowi;
  203. const { user } = req;
  204. const { currentPathname } = props;
  205. // determine pageId
  206. const pageIdStr = currentPathname.substring(1);
  207. const pageId = isValidObjectId(pageIdStr) ? pageIdStr : null;
  208. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  209. const page = result.data;
  210. if (page == null) {
  211. const count = pageId != null ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  212. // check the page is forbidden or just does not exist.
  213. props.isForbidden = count > 0;
  214. props.isNotFound = true;
  215. logger.warn(`Page is ${props.isForbidden ? 'forbidden' : 'not found'}`, currentPathname);
  216. }
  217. else {
  218. // set shouldRedirectToParmalink
  219. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  220. const shouldRedirectToParmalink = !isToppage && !isValidObjectId(pageIdStr);
  221. if (shouldRedirectToParmalink) {
  222. props.currentPathname = `/${page._id}`;
  223. }
  224. }
  225. await (page as unknown as PageModel).populateDataToShowRevision();
  226. props.pageWithMetaStr = JSON.stringify(result);
  227. }
  228. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  229. // const req: CrowiRequest = context.req as CrowiRequest;
  230. // const { crowi } = req;
  231. // const UserModel = crowi.model('User');
  232. // if (isUserPage(props.currentPagePath)) {
  233. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  234. // if (user != null) {
  235. // props.pageUser = JSON.stringify(user.toObject());
  236. // }
  237. // }
  238. // }
  239. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  240. const req: CrowiRequest = context.req as CrowiRequest;
  241. const { crowi } = req;
  242. const {
  243. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  244. } = crowi;
  245. const { user } = req;
  246. const result = await getServerSideCommonProps(context);
  247. // check for presence
  248. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  249. if (!('props' in result)) {
  250. throw new Error('invalid getSSP result');
  251. }
  252. const props: Props = result.props as Props;
  253. await injectPageInformation(context, props);
  254. if (user != null) {
  255. props.currentUser = JSON.stringify(user);
  256. }
  257. props.isSearchServiceConfigured = searchService.isConfigured;
  258. props.isSearchServiceReachable = searchService.isReachable;
  259. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  260. // props.isMailerSetup = mailService.isMailerSetup;
  261. // props.isAclEnabled = aclService.isAclEnabled();
  262. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  263. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  264. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  265. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  266. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  267. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  268. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  269. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  270. // props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  271. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  272. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  273. // props.editorConfig = {
  274. // upload: {
  275. // image: crowi.fileUploadService.getIsUploadable(),
  276. // file: crowi.fileUploadService.getFileUploadEnabled(),
  277. // },
  278. // };
  279. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  280. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  281. return {
  282. props,
  283. };
  284. };
  285. export default GrowiPage;